package com.laolang.pluto.framework.config.security.handler;

import cn.hutool.json.JSONUtil;
import com.laolang.pluto.common.core.domain.common.R;
import com.laolang.pluto.common.util.ServletKit;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

/**
 * @author laolang
 * @date 2021-08-07 03:21
 */
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        R<Object> r = R.failed(exception.getMessage());
        if (exception instanceof BadCredentialsException) {
            r.setMsg("用户名或密码错误");
        }
        ServletKit.writeJson(response, JSONUtil.toJsonStr(r));
    }
}
